/* eslint-disable standard/computed-property-even-spacing */
/* eslint-disable camelcase */
export function timeFix() {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome() {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '调整好心态，控制好情绪', '我猜你可能累了', '多注意休息，别一味苦干']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent() {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader(callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () {}
  window.addEventListener(
    'scroll',
    (event) => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

export function isIE() {
  const bw = window.navigator.userAgent
  const compare = (s) => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate(id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}
export function scorePassword(pass) {
  let score = 0
  if (!pass) {
    return score
  }
  // award every unique letter until 5 repetitions
  const letters = {}
  for (let i = 0; i < pass.length; i++) {
    letters[pass[i]] = (letters[pass[i]] || 0) + 1
    score += 5.0 / letters[pass[i]]
  }

  // bonus points for mixing it up
  const variations = {
    digits: /\d/.test(pass),
    lower: /[a-z]/.test(pass),
    upper: /[A-Z]/.test(pass),
    nonWords: /\W/.test(pass),
  }

  let variationCount = 0
  for (var check in variations) {
    variationCount += variations[check] === true ? 1 : 0
  }
  score += (variationCount - 1) * 10

  return parseInt(score)
}

/**
 * 生成图形验证码
 * @param String target canvas id
 * @param String keys 给定的随机字符串
 */
export function makeCode(options, callback) {
  if (options.target === undefined || options.target === null) return
  callback = callback || function () {}
  let verifyCode = ''
  setTimeout(() => {
    // 随机数
    const rn = (min, max) => {
      return parseInt(Math.random() * (max - min) + min)
    }
    // 随机颜色
    const rc = (min, max) => {
      var r = rn(min, max)
      var g = rn(min, max)
      var b = rn(min, max)
      return `rgb(${r},${g},${b})`
    }
    // 3.填充背景颜色,颜色要浅一点
    const w = 200
    const h = 40
    const ctx = document.querySelector(options.target).getContext('2d')
    ctx.fillStyle = rc(180, 230)
    ctx.fillRect(0, 0, w, h)
    // 4.随机产生字符串
    var pool = options.keys || 'abcdefghijklmnpqrstuvwxyz23456789'
    for (let i = 0; i < 4; i++) {
      var c = pool[rn(0, pool.length)] // 随机的字
      const tempStr = c.concat()
      verifyCode += tempStr.toString()
      var fs = rn(18, 40) // 字体的大小
      var deg = rn(-30, 30) // 字体的旋转角度
      ctx.font = fs + 'px Simhei'
      ctx.textBaseline = 'top'
      ctx.fillStyle = rc(80, 150)
      ctx.save()
      ctx.translate(30 * i + 15, 15)
      ctx.rotate((deg * Math.PI) / 180)
      ctx.fillText(c, -15 + 5, -15)
      ctx.restore()
    }
    // 5.随机产生5条干扰线,干扰线的颜色要浅一点
    for (let i = 0; i < 5; i++) {
      ctx.beginPath()
      ctx.moveTo(rn(0, w), rn(0, h))
      ctx.lineTo(rn(0, w), rn(0, h))
      ctx.strokeStyle = rc(180, 230)
      ctx.closePath()
      ctx.stroke()
    }
    // 6.随机产生40个干扰的小点
    for (let i = 0; i < 40; i++) {
      ctx.beginPath()
      ctx.arc(rn(0, w), rn(0, h), 1, 0, 2 * Math.PI)
      ctx.closePath()
      ctx.fillStyle = rc(150, 200)
      ctx.fill()
    }
    callback(verifyCode)
  }, 100)
}

/**
 *
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/** 判断是否为空
 * @description:
 * @param {*} value
 * @return {(Boolean)}
 */
export const isEmpty = (value) => {
  switch (typeof value) {
    case 'undefined':
      return true
    case 'string':
      if (value.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length === 0) return true
      break
    case 'boolean':
      if (!value) return true
      break
    case 'number':
      if (value === 0 || isNaN(value)) return true
      break
    case 'object':
      if (value === null || value.length === 0) return true
      // eslint-disable-next-line no-unreachable-loop
      for (const i in value) {
        return false
      }
      return true
  }
  return false
}

// bytes文件大小转换
export function bytesToSize(bytes) {
  if (bytes === 0) return '0 B'
  var k = 1024
  var sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  var i = Math.floor(Math.log(bytes) / Math.log(k))

  return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i]
}

/** 限制文件大小
 * @description:
 * @param {Number} size 文件大小
 * @param {String} limitSize 限制大小 50MB
 * @return {(Boolean)}
 */
export function limitFileSzie(size, limitSize) {
  const arr = ['KB', 'MB', 'GB']
  const limit = limitSize.toUpperCase()
  let limitNum = 0
  for (let index = 0; index < arr.length; index++) {
    const leval = limit.indexOf(arr[index])
    if (leval > -1) {
      limitNum = parseInt(limit.substring(0, leval) * Math.pow(1024, index + 1))
      break
    }
  }
  if (size > limitNum) {
    return false
  }
  return true
}

/**
 * download的属性是HTML5新增的属性
 * href属性的地址必须是非跨域的地址，如果引用的是第三方的网站或者说是前后端分离的项目(调用后台的接口)，这时download就会不起作用。
 * 此时，如果是下载浏览器无法解析的文件，例如.exe,.xlsx..那么浏览器会自动下载，但是如果使用浏览器可以解析的文件，比如.txt,.png,.pdf....浏览器就会采取预览模式
 * 所以，对于.txt,.png,.pdf等的预览功能我们就可以直接不设置download属性(前提是后端响应头的Content-Type: application/octet-stream，如果为application/pdf浏览器则会判断文件为 pdf ，自动执行预览的策略)
 */
export function downloadEvt(url, fileName = '未知文件') {
  const el = document.createElement('a')
  el.style.display = 'none'
  el.setAttribute('target', '_blank')

  fileName && el.setAttribute('download', fileName)
  el.href = url
  console.log(el)
  document.body.appendChild(el)
  el.click()
  document.body.removeChild(el)
}

/** 子节点寻找所有父节点
 * @description:
 * @param {Number} tree 树形结构
 * @param {String} func 查找条件
 * @return {(Array)}
 */
export function treeFindPath(tree, func, path = []) {
  if (!tree) return []
  for (const data of tree) {
    path.push(data)
    if (func(data)) return path
    if (data.children) {
      const findChildren = treeFindPath(data.children, func, path)
      if (findChildren.length) return findChildren
    }
    path.pop()
  }
  return []
}

// 生成guid
export function guid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0
    const v = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}

// echarts 图表字体自适应
export function setFontSize(res, n) {
  const clientWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
  if (!clientWidth) return
  // const scale = n || 1.2
  const fontSize = clientWidth / 1920
  return res * fontSize
}
